package com.guardchina.framework.web.filter;

import com.guardchina.framework.util.constant.Constants;
import com.guardchina.framework.util.constant.HeaderKeyConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

/**
 * 描述：日志过滤器
 *
 * @author lwb
 * @date 2019/3/15 13:11
 */
@Slf4j
public class Slf4jTraceFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
      log.info(">>>>>>>>>>>>>>>>>>> Init log trace filter <<<<<<<<<<<<<<<<<");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Optional.ofNullable((HttpServletRequest) request)
                .ifPresent( httpServletRequest -> {
                    MDC.put(Constants.TRACE_ID, UUID.randomUUID().toString().replace("-", ""));
                    if (StringUtils.isNoneBlank(httpServletRequest.getHeader(HeaderKeyConst.USER_ID_KEY))) {
                        MDC.put(HeaderKeyConst.USER_ID_KEY, httpServletRequest.getHeader(HeaderKeyConst.USER_ID_KEY));
                    } else {
                        String userId = httpServletRequest.getParameter(Constants.USER_ID);
                        if (StringUtils.isNotBlank(userId)) {
                            MDC.put(HeaderKeyConst.USER_ID_KEY, userId);
                        }
                    }
                }
                );

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
